--[[
FilePath: \Lua\View\UIActivityExplor\UIExplorGift.lua
游园活动礼包
--]]

require 'View/UIBase/UIBase'

UIExplorGift = UIBase.New(PanelNames.UIExplorGift)
local _M = UIExplorGift

_M.hasInit = false
_M.ContentItems = {}
_M.activeId = nil

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Btn_BgClose"), self.OnBack)

        self.title = self:GetChild("Text_Title");
        self.itemList = self:GetChild("List_Gift");
        self.tipTime = self:GetChild("Text_CountDown");

        _M.hasInit = true

        self.itemList.itemRenderer = self.RefreshItem;

        self:addEvent()
    end
end

function _M:addEvent()
    self:RegisterEvent(Config.EventType.Fresh_Active,self.Refresh);
    --self.btnHelp.onClick:Add(self.HelpTip, self)
end

function _M:removeEvent()
    --self.btnHelp.onClick:Remove(self.HelpTip)
end

function _M:HelpTip()
    if self.tableData ~= nil and self.tableData.f_ExplainTitle ~= nil and self.tableData.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(self.tableData.f_ExplainTitle), tostring(self.tableData.f_ExplainText));
    end
end

-- 显示
function _M:OnEnable()
    self:Refresh();
end

_M.itemConfig = nil;
_M.serverDataTab = nil;
function _M:Refresh()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
        return;
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
    end

    self.serverDataTab = nil;
    if self.itemConfig == nil then
        self.itemConfig = {};
        local config = G.dataTable[tostring(self.tableData.f_ItemTableName)];
        for k, v in pairs(config) do
            if tonumber(v.f_ActivityId) == tonumber(self.activeId) then
                table.insert(self.itemConfig, v)
            end
        end
    end
    table.sort(self.itemConfig, function(a, b)
        return a.f_Order < b.f_Order;
    end)
    self.title.text = getLanguage(self.tableData.f_ActivityName);
    self.itemList.numItems = #self.itemConfig;
    --if self.playEffect then
    --    self.playEffect = false;
    --    HelperFunc.ListTranstionPlay(self.itemList)
    --end

    local time = HelperFunc.GetServerTime();
    self.endCountDown = self.serverData.endTime - time;
    self:updateActiveCountDown();
    self:TimeCall(self.updateActiveCountDown, 1000, -1);
end

function _M:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    local showTimeTips = self.tipTime
    if self.showTimeMode == 2 then
        showTimeTips = self.txtChunjieTips
    end
    if self.endCountDown <= 0 then
        showTimeTips.text = getLanguage("Sys_ActivityEnd");
        self:RemoveTimeCall(self.updateActiveCountDown)
    else
        showTimeTips.text = string.format(getLanguage("ActivityExplorTips09"), HelperFunc.GetSurpTimeStr2(self.endCountDown));
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M.RefreshItem(index, itemObj)
    _M:CreateItem(index, itemObj)
    local config = _M.itemConfig[index + 1];
    _M.ContentItems[index]:OnShow(config, _M:GetServerData(config.f_ItemId))
end

function _M:CreateItem(index,itemObj)
    if self.ContentItems[index] then
        return
    end
    local item = self.UIExplorGiftItem.New()
    self.ContentItems[index] = item;
    item:OnCreate(itemObj,self)
end

function _M:GetServerData(id)
    if self.serverData == nil or self.serverData.param == nil or self.serverData.param.buyCountMap == nil then
        return 0;
    end

    local num = self.serverData.param.buyCountMap[tostring(id)];
    if num == nil then
        return 0;
    else
        return num;
    end
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    if self.ContentItems then
        for key, value in pairs(self.ContentItems) do
            value:OnDestroy();
        end
        self.ContentItems = {};
    end
    self.itemConfig = nil;
    self.hasInit = false;
end

-- item类
_M.UIExplorGiftItem = Class("UIExplorGiftItem",UIComponentInterface)
local _M_T = _M.UIExplorGiftItem
function _M_T:OnCreate(obj,parent)
    self.taskId = 0
    self.parent = parent
    self.fguiObj = obj
    self.isGet = false;
    self.hasNum = 0;

    self.bg = obj:GetChild("Loader_GiftBg");
    self.txtGiftName = obj:GetChild("Loader_GiftName");
    self.numLimit = obj:GetChild("Text_Limit");
    self.btnBuy = obj:GetChild("Btn_Buy");
    self.listReward = obj:GetChild("List_Reward");
    self.limit = obj:GetController("Limit");
    self.soldOutCtrl = obj:GetController("SoldOut");
    self.btnBuy.onClick:Add(function ()
        self:ClickReward();
    end);

end
function _M_T:OnShow(itemConfig, bugNum)
    self.config = itemConfig;
    self.bugNum = tonumber(bugNum);
    self:Refresh();
end

function _M_T:Refresh()
    self.txtGiftName.url = self.config.f_Icon;
    if self.config.f_Price == 0 then
        self.btnBuy.text = getLanguage("FreeMoney");
    else
        if self.config.f_PriceType == EnumConst.CostBuyType.GOLD then
            self.btnBuy.text = string.format("<img src='ui://ItemAtlas/1' width='60' height='60'/> %s", self.config.f_Price);
        else
            self.btnBuy.text = logicMgr.SDKManager.GetProductPriceFormat(self.config.f_ProductId)
        end
    end

    local rewards = decodeJsonStrToTabel(self.config.f_Rewards);
    logicMgr.CostManager.RefreshItemList(self.listReward, rewards);
    local limit = tonumber(self.config.f_Limit);
    if limit > 0 then
        if self.config.f_RefreshType == 2 then
            self.numLimit.text = string.format(getLanguage("ActivityExplorTips11"), (limit - self.bugNum).."/"..limit)
        else
            self.numLimit.text = string.format(getLanguage("ActivityExplorTips10"), (limit - self.bugNum).."/"..limit)
        end

        self.limit.selectedIndex = 0
        if self.bugNum >= limit then
            self.soldOutCtrl.selectedIndex = 1;
            self.hasNum = 0;
        else
            self.soldOutCtrl.selectedIndex = 0;
            self.hasNum = 1;
        end
    else
        self.limit.selectedIndex = 1
    end
end

function _M_T:OnHide()

end
function _M_T:OnDestroy()
    self.btnBuy.onClick:Clear();
end

function _M_T:ClickReward()
    if self.isGet or self.hasNum <= 0 then
        return;
    end

    self.isGet = true;
    if self.config.f_PriceType == EnumConst.CostBuyType.RMB then
       -- TAManager.TrackActivityEvent(_M.activeId, EnumConst.ActivityTrack.BuyGift, self.config.f_ItemId)
        logicMgr.CostManager.BuyCostType(_M.activeId, {self.config.f_ItemId}, self.config.f_ProductId, 1, 2, self.config.f_Price, nil, self);
    elseif self.config.f_PriceType == EnumConst.CostBuyType.GOLD then
        if logicMgr.ItemManager.getBagNumByTableID(CurrencyEnum.GOLD) >= self.config.f_Price then
            local rewards = decodeJsonStrToTabel(self.config.f_Rewards);
            local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
            pop.Init(105, function (flag)
                if flag then
                  --  TAManager.TrackActivityEvent(_M.activeId, EnumConst.ActivityTrack.BuyGift, self.config.f_ItemId)
                    ActivityHandler.sendReqBuyByGoldMessage(_M.activeId, 0, {self.config.f_ItemId})
                end
            end, self.config.f_Price,G.dataTable["t_item"][tostring(rewards[1][1])].f_Icon, rewards[1][2])--, logicMgr.ItemManager.GetItemName(rewards[1][1]))
        else
            UISysTips.AddMsg(getLanguage("Character_Tips7"));
        end
    end

    --costHandler.reqBuyCost(tonumber(_M.activeId), {self.config.f_ItemId}, self.config.f_ProductId, 1, 2);
    self:TimeCall(self.TimeEnd, 100);
end

function _M_T:TimeEnd()
    self:RemoveTimeCall(self.TimeEnd)
    self.isGet = false;
end

return _M;